package ext.tianma.part;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;

import wt.change2.WTChangeOrder2;
import wt.clients.vc.CheckInOutTaskLogic;
import wt.doc.WTDocument;
import wt.enterprise.EnterpriseHelper;
import wt.enterprise.MadeFromLink;
import wt.enterprise.RevisionControlled;
import wt.fc.Identified;
import wt.fc.IdentityHelper;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.WTObject;
import wt.fc.collections.WTValuedHashMap;
import wt.folder.CabinetBased;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.iba.value.service.LoadValue;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.inf.library.WTLibrary;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.State;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.LineNumber;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.Source;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartMasterIdentity;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.query.ClassAttribute;
import wt.query.OrderBy;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.type.TypedUtility;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewException;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import wt.vc.wip.Workable;

import com.ptc.core.meta.common.TypeIdentifier;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.part.CusIBAUtil;
import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.eco.ECOCRUDUtil;
import ext.tianma.part.imported.ImportedExcelUtil;

public class PartCommands implements RemoteAccess, Serializable {
	public static boolean VERBOSE = true;
	public static WTProperties wtProperties;
	public static String CLASSNAME = "";
	static {
		CLASSNAME = PartCommands.class.getName();
		try {
			wtProperties = WTProperties.getLocalProperties();
			// VERBOSE = wtProperties.getProperty("ext.tianma.part.verbose",
			// true);
		} catch (java.io.IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * 原材料生成物料号
	 * 
	 * @param obj PBO
	 * @throws WTException
	 * @throws IOException
	 * @throws WTPropertyVetoException
	 * @throws InvalidFormatException
	 * @throws NumberFormatException
	 */
	public static void generateRowMaterialNumber(WTObject obj)
			throws WTException, IOException, WTPropertyVetoException, InvalidFormatException, NumberFormatException {
		String number = "";
		String laftNumber = "";
		WTPart orgPart = null;
		Workbook we = null;
		InputStream in = null;
		String path = (WTProperties.getLocalProperties()).getProperty("ext.tianma.cfg.RawMaterialsAndClassCode");
		in = new FileInputStream(path);
		we = WorkbookFactory.create(in);
		if (null == path || path.equals("")) {
			throw new WTException("没有获取到原材料代码及类别的配置路径，请检查!");
		}
		if (null == in || null == we) {
			throw new WTException("没有获取到原材料代码及类别的配置文件，请检查");
		}
		if (obj instanceof WTPart) {

			WTPart part = (WTPart) obj;
			String softType = IBAUtil.getSoftType(part).getLogicalIdentifier();
			softType = softType.substring(softType.lastIndexOf(".") + 1);

			String eName = (String) IBAUtil.getIBAValue(part, "partEName");
			if (null == eName || eName.equals("")) {
				throw new WTException("没有获取到原材料的英文名称，无法生成编码！");
			}
			String seqName = getSequenceName(we.getSheetAt(2), eName);
			if (null == seqName || seqName.equals("")) {
				throw new WTException("没有获取到对应的序列名称，请从检查英文名称在配置表中是否存在！");
			}
			if (VERBOSE) {
				System.out.println("Debug 生成原材料编码   物料英文名称：" + eName);
				System.out.println("Debug 生成原材料编码    获取到的序列名称：" + seqName);
				System.out.println("Debug 生成原材料编码   物料原始编号：" + part.getNumber());
				System.out.println("Debug 生成原材料编码    物料的类型：" + softType);
			}
			WTPart exitPart;
			part = getWTPartByNumViewAndVersion(part.getNumber(), "Design", "0.0");
			QueryResult qr = PersistenceHelper.manager.navigate(part, "original", MadeFromLink.class, false);
			if ((qr == null) || (qr.size() == 0)) {
				laftNumber = "0";
			} else {
				while (qr.hasMoreElements()) {
					MadeFromLink link = (MadeFromLink) qr.nextElement();

					orgPart = (WTPart) link.getOriginal();
				}
				String orgNumber = orgPart.getNumber();
				if ((orgNumber != null) && (!orgNumber.trim().isEmpty())) {
					laftNumber = orgNumber.substring(orgNumber.length() - 1);
				}
			}
			part = CoreUtil.getWTPartByNumberAndView(part.getNumber(), part.getViewName());
			do {
				if (softType.equals("RawMaterial")) {
					String bigClass = "1";

					String littleClass = getLitteClassCode(we.getSheetAt(0), eName);
					if (VERBOSE) {
						System.out.println("Debug 生成原材料编码    英文名称：" + eName);
						System.out.println("Debug 生成原材料编码   小类码：" + littleClass);
					}
					if ((littleClass == null) || (littleClass.equals(""))) {
						throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
					}

					String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
					if (VERBOSE) {
						System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
					}
					NumberFormat nf = NumberFormat.getInstance();
					nf.setMinimumIntegerDigits(6);
					nf.setMaximumIntegerDigits(6);
					nf.setGroupingUsed(false);
					waterCode = nf.format(Integer.parseInt(waterCode.trim()));

					number = bigClass + littleClass + waterCode + laftNumber;
					/**
					 * @author xuge_ning
					 * @reason:新增TopPolarizer和BotPolarizer物料类型，同属于偏光片。
					 */
				} else if (softType.equals("Polarizer") || softType.equals("TopPolarizer")
						|| softType.equals("BotPolarizer")) {
					String polarizerType = (String) IBAUtil.getIBAValue(part, "partCName");
					System.out.println("Debug 生成原材料编码   偏光片的类型：" + polarizerType);
					if ((polarizerType != null) && (polarizerType.equals("偏光片TOP"))) {
						String bigClass = "1";

						String littleClass = getLitteClassCode(we.getSheetAt(0), eName);
						System.out.println("Debug 生成原材料编码    小类码：" + littleClass);
						if ((littleClass == null) || (littleClass.equals(""))) {
							throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
						}
						String waterCode = null;
						int count;
						do {
							waterCode = PersistenceHelper.manager.getNextSequence(seqName);
							System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
							count = Integer.parseInt(waterCode);
						} while (count % 2 != 1);

						NumberFormat nf = NumberFormat.getInstance();
						nf.setMinimumIntegerDigits(6);
						nf.setMaximumIntegerDigits(6);
						nf.setGroupingUsed(false);
						waterCode = nf.format(Integer.parseInt(waterCode.trim()));

						number = bigClass + littleClass + waterCode + laftNumber;
					} else if ((polarizerType != null) && (polarizerType.equals("偏光片BOTTOM"))) {
						String bigClass = "1";

						String littleClass = getLitteClassCode(we.getSheetAt(0), eName);
						System.out.println("Debug 生成原材料编码    小类码：" + littleClass);
						if ((littleClass == null) || (littleClass.equals(""))) {
							throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
						}
						String waterCode = null;
						int count;
						do {
							waterCode = PersistenceHelper.manager.getNextSequence(seqName);
							System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
							count = Integer.parseInt(waterCode);
						} while (count % 2 != 0);

						NumberFormat nf = NumberFormat.getInstance();
						nf.setMinimumIntegerDigits(6);
						nf.setMaximumIntegerDigits(6);
						nf.setGroupingUsed(false);
						waterCode = nf.format(Integer.parseInt(waterCode.trim()));

						number = bigClass + littleClass + waterCode + laftNumber;
					} else {
						String bigClass = "1";

						String littleClass = getLitteClassCode(we.getSheetAt(0), eName);
						System.out.println("Debug 生成原材料编码  小类码：" + littleClass);
						if ((littleClass == null) || (littleClass.equals(""))) {
							throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
						}

						String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
						NumberFormat nf = NumberFormat.getInstance();
						nf.setMinimumIntegerDigits(6);
						nf.setMaximumIntegerDigits(6);
						nf.setGroupingUsed(false);
						waterCode = nf.format(Integer.parseInt(waterCode.trim()));

						number = bigClass + littleClass + waterCode + laftNumber;
					}
				} else if (softType.equals("PhantomPolarizer")) {
					String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
					NumberFormat nf = NumberFormat.getInstance();
					nf.setMinimumIntegerDigits(6);
					nf.setMaximumIntegerDigits(6);
					nf.setGroupingUsed(false);
					waterCode = nf.format(Integer.parseInt(waterCode.trim()));

					number = "POL" + waterCode + laftNumber;
				}

				exitPart = getWTPartByNumber(number);
			} while (exitPart != null);

			System.out.println("Debug 生成原材料编码   生成的物料号为：" + number);
			Identified partidentified = (Identified) part.getMaster();
			WTPartMasterIdentity partmasteridentity = (WTPartMasterIdentity) partidentified.getIdentificationObject();
			partmasteridentity.setNumber(number);
			partidentified = IdentityHelper.service.changeIdentity(partidentified, partmasteridentity); // 更新名称
			PersistenceServerHelper.manager.update(partidentified);
			part = (WTPart) PersistenceHelper.manager.refresh(part);
			System.out.println("Debug 生成原材料编码   生成的物料号为：" + part.getNumber());
		}

	}

	/**
	 * 将原材料的审核信息设置到ＩＢＡ中
	 * 
	 * @param supplier 供应商
	 * @param prcie    价格
	 * @param currency 币种
	 * @param delivery 日交货能力
	 * @param landT    Ｌ／Ｔ
	 * @param order    最小订单
	 * @param pack     最小包装
	 * @param obj      签审兑现
	 * @throws WTException
	 */
	public static void setRawMaterialAuditInfoToIBA(String supplier, String prcie, String currency, String delivery,
			String landT, String order, String pack, WTObject obj) throws WTException {
		if (obj instanceof WTObject) {
			System.out.println("Debug 原材料编码申请流程     设置IBA 供应商：" + supplier);
			System.out.println("Debug 原材料编码申请流程     设置IBA 价格：" + prcie);
			System.out.println("Debug 原材料编码申请流程     设置IBA 币种：" + currency);
			System.out.println("Debug 原材料编码申请流程     设置IBA 日交货能力：" + delivery);
			System.out.println("Debug 原材料编码申请流程     设置IBA L/T：" + landT);
			System.out.println("Debug 原材料编码申请流程     设置IBA 最小订货量：" + order);
			System.out.println("Debug 原材料编码申请流程     设置IBA 最小包装：" + pack);
			WTPart part = (WTPart) obj;
			Hashtable<String, String> table = new Hashtable<String, String>();
			// 注释代码存在添加空指针异常
			// table.put("partSupplierWithSystemName", supplier);
			// table.put("partStandardCost", prcie);
			// table.put("partCostUnit", currency);
			// table.put("partDateDelivery", delivery);
			// table.put("partLT", landT);
			// table.put("partMinOrderQty", order);
			// table.put("partMinPackage", pack);
			// IBAUtil.setSoftTypeIBAValues(part, table);
			// 改后代码排除空指针异常
			addToHashtable(table, "partSupplierWithSystemName", supplier);
			addToHashtable(table, "partStandardCost", prcie);
			addToHashtable(table, "partCostUnit", currency);
			addToHashtable(table, "partDateDelivery", delivery);
			addToHashtable(table, "partLT", landT);
			addToHashtable(table, "partMinOrderQty", order);
			addToHashtable(table, "partMinPackage", pack);
			IBAUtil.setSoftTypeIBAValues(part, table);

		} else {
			throw new WTException("主要业务对象不是WTPart，不能设置ＩＢＡ，请检查");
		}
	}

	/**
	 * 获取物料代码
	 * 
	 * @param sheet sheet对象
	 * @param EName 英文名称
	 * @return 物料代码
	 * @throws WTException
	 */
	public static String getLitteClassCode(Sheet sheet, String EName) throws WTException {
		String code = null;
		for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
			Row row = sheet.getRow(i);
			String temp = getCellValue(row.getCell(2)).trim();
			if (null == temp || temp.equals("")) {
				continue;
			} else {
				if (temp.equals(EName)) {
					code = getCellValue(row.getCell(1));

				}
			}
		}
		return code;
	}

	/**
	 * 获取序列名称
	 * 
	 * @param sheet sheet对象
	 * @param EName 英文名称
	 * @return 序列名称
	 * @throws WTException
	 */
	public static String getSequenceName(Sheet sheet, String EName) throws WTException {
		// XSSFSheet sheet = we.getSheetAt(0);
		String code = null;
		for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
			Row row = sheet.getRow(i);
			String temp = getCellValue(row.getCell(2)).trim();
			// System.out.println("temp:"+temp);
			if (null == temp || temp.equals("")) {
				continue;
			} else {
				if (temp.equals(EName)) {
					code = getCellValue(row.getCell(1)).trim();

				}
			}
		}
		return code;
	}

	/**
	 * 获取单元格中的信息
	 * 
	 * @param cell 单元格
	 * @return 主要参数信息
	 * @throws Exception
	 */
	public static String getCellValue(Cell cell) throws WTException {
		String value = "";
		try {
			if (null == cell) {
				return "";
			}
			switch (cell.getCellType()) {
			case XSSFCell.CELL_TYPE_NUMERIC:
				value = Double.toString(cell.getNumericCellValue());
				break;
			case XSSFCell.CELL_TYPE_STRING:
				value = cell.getStringCellValue();
				break;
			case XSSFCell.CELL_TYPE_BLANK:
				value = "";
				break;
			case XSSFCell.CELL_TYPE_BOOLEAN:
				value = Boolean.toString(cell.getBooleanCellValue());
				break;
			case XSSFCell.CELL_TYPE_FORMULA:
				try {
					value = String.valueOf(cell.getNumericCellValue());
				} catch (Exception e) {
					value = cell.getStringCellValue();
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}
		// System.out.println("excel 单元格的值："+value);
		if (value.indexOf(".") != -1) {
			value = value.substring(0, value.indexOf("."));
		}
		return value.trim();
	}

	/**
	 * 根据零部件编号获取最新版本的零部件
	 * 
	 * @param partNumber 零部件编号
	 * @return 返回该编号对应的零部件的最新版本。如果零部件不存在，返回空；如果零部件编号为空，返回空
	 * @throws WTException <br>
	 *                     <br>
	 */
	public static WTPart getWTPartByNumber(String partNumber) throws WTException {
		char[] chars = partNumber.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			chars[i] = toUpper(chars[i]);
		}
		String number = new String(chars);
		WTPart part = null;
		QuerySpec qs = null;
		QueryResult qr = null;
		qs = new QuerySpec(WTPartMaster.class);
		// 根据零件编号查询
		SearchCondition sc = new SearchCondition(WTPartMaster.class, "number", SearchCondition.LIKE, number);
		qs.appendSearchCondition(sc);
		qr = PersistenceHelper.manager.find(qs);
		if (qr.hasMoreElements()) {
			WTPartMaster master = (WTPartMaster) qr.nextElement();
			part = getLatestPartByPartMaster(master);
		}
		return part;
	}

	/**
	 * 根据零部件的master，获取零部件的最新小版本
	 * 
	 * @param partMaster 想要获取最新小版本的零部件的master
	 * @return 返回该master对应的最新小版本的零部件，如果master为空，返回空
	 * @throws WTException
	 */
	public static WTPart getLatestPartByPartMaster(WTPartMaster partMaster) throws WTException {
		Iterated iter = null;
		boolean flag = false;
		LatestConfigSpec latestconfigspec = new LatestConfigSpec();
		// 根据零部件的master和 latestconfigspec得到该master的所有小版本
		QueryResult queryresult = ConfigHelper.service.filteredIterationsOf(partMaster, latestconfigspec);
		if (queryresult != null && queryresult.size() <= 0) {
			ConfigSpec configspec = ConfigHelper.service.getDefaultConfigSpecFor(WTPartMaster.class);
			queryresult = ConfigHelper.service.filteredIterationsOf(partMaster, configspec);
		}

		while (queryresult.hasMoreElements() && (!flag)) {
			iter = (Iterated) (queryresult.nextElement());
			flag = iter.isLatestIteration();
		}
		return (WTPart) iter;
	}

	/**
	 * 根据旧物料另存为一个新物料
	 * 
	 * @param oldPart 就物料
	 * @return 新物料
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static WTPart saveNewPart(WTPart oldPart) throws WTException, WTPropertyVetoException {
		String newPartName = oldPart.getName();
		String newPartView = "Design";

		// String foldPath = oldPart.getFolderPath();//最后一对象结尾
		// if (!"/Default".equals(foldPath)) {
		// int lastIndex = foldPath.lastIndexOf("/");
		// foldPath = foldPath.substring(0, lastIndex);
		// }
		// 修改原因:此方法难道对象所在的文件夹路径不包含对象
		String foldPath = oldPart.getLocation();

		WTContainer container = oldPart.getContainer();
		Folder folder = FolderHelper.service.getFolder(foldPath, WTContainerRef.newWTContainerRef(container));
		WTPart newPart = (WTPart) EnterpriseHelper.service.newCopy(oldPart);
		newPart.setName(newPartName);
		View view = ViewHelper.service.getView(newPartView);
		ViewReference viewRef = ViewReference.newViewReference(view);
		newPart.setView(viewRef);
		newPart.setContainer(container);
		if (folder != null) {
			FolderHelper.assignLocation(newPart, folder);
		}
		newPart = (WTPart) EnterpriseHelper.service.saveCopy(oldPart, newPart);

		// 删除所有关联的文档的Link关系
		PartRelatedDocUtil.removeAllRelatedDocs(newPart);
		return newPart;

	}

	/**
	 * 获取PBO的供应信息
	 * 
	 * @param obj pBO
	 * @return 获取供应商信息
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static Hashtable<String, String> getSupplierInfo(Persistable obj) throws RemoteException, WTException {
		Hashtable<String, String> table = new Hashtable<String, String>();
		if (obj instanceof WTPart) {
			/*
			 * table.put("partSupplierWithSystemName", supplier);
			 * table.put("partStandardCost", prcie); table.put("partCostUnit", currency);
			 * table.put("partDateDelivery", delivery); table.put("partLT", landT);
			 * table.put("partMinOrderQty", order); table.put("partMinPackage", pack);
			 */
			WTPart part = (WTPart) obj;

			Hashtable ibaTable = IBAUtil.getIBAValues(part);
			String supplier = (String) ibaTable.get("partSupplierWithSystemName");
			if (null == supplier)
				supplier = "";

			String prcie = (String) ibaTable.get("partStandardCost");
			if (null == prcie)
				prcie = "";

			String currency = (String) ibaTable.get("partCostUnit");
			if (null == currency)
				currency = "";

			String delivery = (String) ibaTable.get("partDateDelivery");
			if (null == delivery)
				delivery = "";

			String landT = (String) ibaTable.get("partLT");
			if (null == landT)
				landT = "";

			String order = (String) ibaTable.get("partMinOrderQty");
			if (null == order)
				order = "";

			String pack = (String) ibaTable.get("partMinPackage");
			if (null == pack)
				pack = "";

			table.put("supplier", supplier);
			table.put("prcie", prcie);
			table.put("currency", currency);
			table.put("delivery", delivery);
			table.put("landT", landT);
			table.put("order", pack);
			table.put("pack", pack);

			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   供应商：" + supplier);
			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   价格：" + prcie);
			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   币种：" + currency);
			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   日交货能力：" + delivery);
			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   L/T：" + landT);
			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   最小订货量：" + order);
			System.out.println("Debug 版本进阶流程    获取PBO 供应商信息   最小包装：" + pack);

		}
		return table;

	}

	/**
	 * 版本进阶时获取信息的料号
	 * 
	 * @param oldnumber 就得好的前几位
	 * @param type      物料的类型是否为C4
	 * @return 新的料号
	 * @throws WTException
	 * @throws IOException
	 * @throws InvalidFormatException
	 */
	public static String getVersionPromoteNewNumber(String oldnumber, String type)
			throws WTException, InvalidFormatException, IOException {
		WTPartMaster master = null;
		QuerySpec qs = null;
		QueryResult qr = null;
		String number = null;
		String newVersionNumber = null;
		String newNumber = null;
		qs = new QuerySpec(WTPartMaster.class);
		// 定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, "number", SearchCondition.LIKE, oldnumber + "_");
		qs.appendSearchCondition(sc);
		// 修改原因:历史数据导入时的先后顺序是没有规律的，若按照数据库中的录入时间来获取当前编号的最大版会有误。
		// 创建时间
		// OrderBy orderby = new OrderBy(new ClassAttribute(WTPartMaster.class,
		// "thePersistInfo.createStamp"), true);
		// 编号
		OrderBy orderby = new OrderBy(new ClassAttribute(WTPartMaster.class, "number"), true);
		qs.appendOrderBy(orderby);
		qr = PersistenceHelper.manager.find(qs);
		if (qr.hasMoreElements()) {
			master = (WTPartMaster) qr.nextElement();
			// System.out.println("################获取到的物料编号："+master.getNumber());
			number = master.getNumber();
			System.out.println("Debug 版本进阶流程   生成新的料号  系统中最大的料号：" + master.getNumber());
		} else {
			throw new WTException("版本进阶   没有获取到旧的物料号");
		}
		String lastNumber = number.substring(number.length() - 1);
		System.out.println("Debug 版本进阶流程   生成新的料号 系统中最大的料号最后一位为：" + lastNumber);
		newVersionNumber = getVersionNumber(0, lastNumber);
		newNumber = oldnumber + newVersionNumber;
		System.out.println("Debug 版本进阶流程   生成新的料号为：" + newNumber);
		return newNumber;

	}

	/**
	 * 根据旧的版本号获取新的版本号 除了C4类型,其他类型的物料
	 * 
	 * @param cellNumber       要读取的列
	 * @param oldVersionNumber 旧的版本号
	 * @return 新的版本号
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws WTException
	 */
	public static String getVersionNumber(int cellNumber, String oldVersionNumber)
			throws IOException, InvalidFormatException, WTException {
		System.out.println("Debug 版本进阶流程  已经用掉的版本号为：" + oldVersionNumber);
		System.out.println("Debug      需读取的列:" + cellNumber);
		Workbook we = null;
		InputStream in = null;
		String newVersionNumber = null;
		String path = (WTProperties.getLocalProperties()).getProperty("ext.tianma.cfg.RawMaterialsAndClassCode");
		in = new FileInputStream(path);
		we = WorkbookFactory.create(in);
		if (null == path || path.equals("")) {
			throw new WTException("没有获取到原材料代码及类别的配置路径，请检查!");
		}
		if (null == in || null == we) {
			throw new WTException("没有获取到原材料代码及类别的配置文件，请检查");
		}
		Sheet sheet = we.getSheetAt(1);
		for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
			Row row = sheet.getRow(i);
			String temp = getCellValue(row.getCell(cellNumber));
			System.out.println("Debug 版本进阶流程  从EXcel中获取到的版本号：" + temp);
			if (temp.equals(oldVersionNumber)) {
				Row row1 = sheet.getRow(i + 1);
				System.out.println("Debug     row1.getCell(cellNumber):" + row1.getCell(cellNumber));
				newVersionNumber = getCellValue(row1.getCell(cellNumber));
				break;
			}
		}
		System.out.println("Debug      newVersionNumber=" + newVersionNumber);
		if (null == newVersionNumber || newVersionNumber.equals("")) {
			throw new WTException("版本进阶时没有重Excel中获取到新的版本号");
		}
		System.out.println("Debug 版本进阶流程  新的版本号：" + newVersionNumber);

		return newVersionNumber;
	}

	/**
	 * 根据旧的版本号获取新的版本号 C4类型的物料
	 * 
	 * @param oldVersionNumber 旧的版本号
	 * @return 新的版本号
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws WTException
	 */
	public static String getVersionNumber(String oldVersionNumber)
			throws IOException, InvalidFormatException, WTException {
		String newVersionNumber = "";

		if ((oldVersionNumber == null) || (oldVersionNumber.trim().isEmpty())) {
			return newVersionNumber;
		}

		String subNumber = oldVersionNumber.trim().substring(oldVersionNumber.trim().length() - 1);
		System.out.println("Debug   原始零部件的编号的最后一位：" + subNumber);
		Workbook we = null;
		InputStream in = null;
		String path = WTProperties.getLocalProperties().getProperty("ext.tianma.cfg.RawMaterialsAndClassCode");
		in = new FileInputStream(path);
		we = WorkbookFactory.create(in);
		if ((path == null) || (path.equals(""))) {
			throw new WTException("没有获取到原材料代码及类别的配置路径，请检查!");
		}
		if ((in == null) || (we == null)) {
			throw new WTException("没有获取到原材料代码及类别的配置文件，请检查");
		}

		Sheet sheet = we.getSheetAt(1);
		int count = 0;
		for (int i = 1; i < sheet.getLastRowNum() + 1;) {
			Row row = sheet.getRow(i);

			if (row != null) {
				String vaString = ImportedExcelUtil.getCellValueAsString(row.getCell(1), true);
				if ((vaString == null) || (vaString.trim().isEmpty())) {
					i++;
				} else if (vaString.trim().equals(subNumber)) {
					count = i;
					i++;
				} else if ((!vaString.trim().equals(subNumber)) && (count == 0)) {
					i++;
				} else {
					if ((count == 5) || ((count < 5) && (i > 5))) {
						throw new WTException("当前C4物料的编号已经是最大编号，不能进行版本进阶升级。");
					}
					if ((count == 10) || ((count > 5) && (count < 10) && (i > 10)))
						throw new WTException("当前C4物料的编号已经是最大编号，不能进行版本进阶升级。");
					if (count == 15) {
						throw new WTException("当前C4物料的编号已经是最大编号，不能进行版本进阶升级。");
					}

					System.out.println("Debug   获取到的原物料最后一位在Excel的位置：" + count);
					String subStr = oldVersionNumber.substring(0, oldVersionNumber.length() - 1);
					subStr = subStr + vaString;
					System.out.println("Debug   版本进阶生成C4的新料号：" + subStr);
					if ((count >= 1) && (count <= 5)) {
						if (checkPartExistence(subStr)) {
							i++;
						} else {
							newVersionNumber = subStr;
							break;
						}
					} else if ((count >= 6) && (count <= 10)) {
						if (checkPartExistence(subStr)) {
							i++;
						} else {
							newVersionNumber = subStr;
							break;
						}
					} else if (count >= 11) {
						if (checkPartExistence(subStr)) {
							i++;
						} else {
							newVersionNumber = subStr;
							break;
						}
					}
				}
			}
		}
		System.out.println("Debug      newVersionNumber=" + newVersionNumber);
		if ((newVersionNumber == null) || (newVersionNumber.trim().isEmpty())) {
			throw new WTException("版本进阶时没有重Excel中获取到新的版本号");
		}

		return newVersionNumber;
	}

	private static boolean checkPartExistence(String number) throws WTException {
		boolean checkPartExistence = false;

		if ((number == null) || (number.trim().isEmpty())) {
			return checkPartExistence;
		}

		WTPartMaster master = CoreUtil.getWTPartMasterByNumber(number);

		if (master != null) {
			checkPartExistence = true;
		}

		return checkPartExistence;
	}

	/**
	 * 生成版本进阶编号
	 * 
	 * @param obj pdo
	 * @throws WTException
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws WTPropertyVetoException
	 */
	public static void generateVersionPromoteNumber(WTObject obj)
			throws WTException, InvalidFormatException, IOException, WTPropertyVetoException {
		if (obj instanceof WTObject) {
			String newNumber = null;
			WTPart or = null;
			WTPart part = (WTPart) obj;
			System.out.println("Debug   current ban ben1 :" + part.getIterationDisplayIdentifier().toString());
			System.out.println("Debug 版本进阶流程 流程主对象随机编号为：" + part.getNumber());

			part = getWTPartByNumViewAndVersion(part.getNumber(), "Design", "0.0");
			if (part == null) {
				System.out.println("Debug  获取到的初始版本的部件为空！");
			}

			QueryResult qr = PersistenceHelper.manager.navigate(part, "original", MadeFromLink.class, false);
			System.out.println("Debug   current ban ben2 :" + part.getIterationDisplayIdentifier().toString());
			if (null == qr || qr.size() == 0) {
				throw new WTException("版本进阶，没有从当前部件获取到原有的部件");
			}
			while (qr.hasMoreElements()) {
				MadeFromLink link = (MadeFromLink) qr.nextElement();
				// WTPart copy= (WTPart) link.getCopy();
				or = (WTPart) link.getOriginal();
				System.out.println("Debug 版本进阶流程  获取到的另存为原部件为：" + or.getNumber());
			}

			String number = or.getNumber();
			number = number.substring(0, number.length() - 1);
			String softType = IBAUtil.getSoftType(part).getLogicalIdentifier();
			// String softTypeName = IBAUtil.getSoftType(part).getDisplayName();
			// String softDesc = IBAUtil.getSoftType(part).getDescription();
			softType = softType.substring(softType.lastIndexOf(".") + 1);
			System.out.println("Debug 版本进阶流程    物料的类型：" + softType);
			if (softType.equals("C4")) {
				newNumber = getVersionNumber(or.getNumber());
			} else {
				newNumber = getVersionPromoteNewNumber(number, "other");
			}
			Identified partidentified = (Identified) part.getMaster();
			WTPartMasterIdentity partmasteridentity = (WTPartMasterIdentity) partidentified.getIdentificationObject();
			partmasteridentity.setNumber(newNumber);
			partidentified = IdentityHelper.service.changeIdentity(partidentified, partmasteridentity); // 更新名称
			PersistenceServerHelper.manager.update(partidentified);
			part = (WTPart) PersistenceHelper.manager.refresh(part);
		}
	}

	/**
	 * 对当前部件及其所有的子件设置生效地IBA
	 * 
	 * @param part       部件
	 * @param configSpec 配置视图规范
	 * @throws WTException
	 * @throws Exception
	 */
	public static void setEffectiveSiteOfFinishGood(WTPart part, WTPartStandardConfigSpec configSpec, String factorys)
			throws WTException, Exception {
		// 获取part的第一层子件
		System.out.println("Debug  版本进阶  当前设置生效地IBA的物料为：" + part.getNumber());
		String factoryIBA = "";
		String setfactoryIBA = "";
		String[] factoryArray = factorys.split(",");
		Vector factoryIBAVectot = IBAUtil.getIBAValue2(part, "partNumberEffectiveSite");
		System.out.println(">>>>>>>>>>>>factorys:" + factorys);
		if (null == factoryIBAVectot || factoryIBAVectot.size() == 0) {

		} else {
			for (int n = 0; n < factoryIBAVectot.size(); n++) {
				String temp = (String) factoryIBAVectot.get(n);
				if (factoryIBA.equals("")) {
					factoryIBA = temp;
				} else {
					factoryIBA = factoryIBA + "," + temp;
				}

			}
		}

		System.out.println("Debug jie gou zhuan chang  shengxiao di shuxing ：" + factoryIBA);
		if (null == factoryIBA || factoryIBA.equals("")) {
			setfactoryIBA = factorys;
		} else {
			setfactoryIBA = factoryIBA;

			for (int n = 0; n < factoryArray.length; n++) {
				String factory = factoryArray[n];
				System.out.println(">>>>>>>>>>>>>>>>factory:" + factory);
				if (factoryIBA.contains(factory)) {
					continue;
				} else {
					setfactoryIBA = setfactoryIBA + "," + factory;
				}
			}
		}
		System.out.println("新的生效地属性值：" + setfactoryIBA);
		CusIBAUtil.forceSetEnumIBAValue(part, "partNumberEffectiveSite", setfactoryIBA);
		QueryResult qr = WTPartHelper.service.getUsesWTParts(part, configSpec);
		if (qr.size() == 0) {
		} else {
			while ((qr != null) && (qr.hasMoreElements())) {
				WTPart wtpart = null;
				Persistable[] apersistable = (Persistable[]) qr.nextElement();
				// WTPartUsageLink usageLink = (WTPartUsageLink)
				// apersistable[0];
				if ((apersistable[1] instanceof WTPart)) {
					wtpart = (WTPart) apersistable[1];
				} else if ((apersistable[1] instanceof WTPartMaster)) {
					WTPartMaster wtpartmaster = (WTPartMaster) apersistable[1];
					wtpart = CoreUtil.getWTPartByMasterAndView(wtpartmaster, "Design");
				}
				setEffectiveSiteOfFinishGood(wtpart, configSpec, factorys);
			}
		}
	}

	/**
	 * 对当前部件及其所有的子件设置生效地IBA
	 * 
	 * @param part       部件
	 * @param configSpec 配置视图规范
	 * @throws WTException
	 * @throws Exception
	 */
	public static void setEffectiveSite(WTPart part, WTPartStandardConfigSpec configSpec, String factory)
			throws WTException, Exception {
		// 获取part的第一层子件
		System.out.println("Debug  版本进阶  当前设置生效地IBA的物料为：" + part.getNumber());

		Vector ibaVector = IBAUtil.getIBAValue2(part, "partNumberEffectiveSite");
		if (null == ibaVector || ibaVector.size() == 0) {
			// 多值枚举类型IBA属性设值
			IBAUtil.forceSetIBAValue(part, "partNumberEffectiveSite", factory);
			// CusIBAUtil.forceSetEnumIBAValue(part, "partNumberEffectiveSite",
			// factory);
		} else {
			String ibas = "";
			for (int i = 0; i < ibaVector.size(); i++) {
				String temp = (String) ibaVector.get(i);
				ibas = ibas + temp + ",";

			}
			// 多值枚举类型IBA属性设值
			// IBAUtil.forceSetIBAValue(part, "partNumberEffectiveSite", ibas +
			// factory);
			CusIBAUtil.forceSetEnumIBAValue(part, "partNumberEffectiveSite", ibas + factory);
		}

		QueryResult qr = WTPartHelper.service.getUsesWTParts(part, configSpec);
		if (qr.size() == 0) {
		} else {
			while ((qr != null) && (qr.hasMoreElements())) {
				WTPart wtpart = null;
				Persistable[] apersistable = (Persistable[]) qr.nextElement();
				// WTPartUsageLink usageLink = (WTPartUsageLink)
				// apersistable[0];
				if ((apersistable[1] instanceof WTPart)) {
					wtpart = (WTPart) apersistable[1];
				} else if ((apersistable[1] instanceof WTPartMaster)) {
					WTPartMaster wtpartmaster = (WTPartMaster) apersistable[1];
					wtpart = CoreUtil.getWTPartByMasterAndView(wtpartmaster, "Design");
				}
				setEffectiveSite(wtpart, configSpec, factory);
			}
		}
	}

	/**
	 * 配置设计视图规范
	 * 
	 * @return
	 * @throws WTException
	 * @throws ViewException
	 * @throws WTPropertyVetoException
	 */
	public static WTPartStandardConfigSpec getConfigSpec() throws ViewException, WTException, WTPropertyVetoException {
		View viewObj = ViewHelper.service.getView("Design");
		WTPartStandardConfigSpec standardConfig = WTPartHelper.service.findWTPartConfigSpec().getStandard();
		standardConfig.setView(viewObj);
		return standardConfig;
	}

	/**
	 * 配置设计视图规范
	 * 
	 * @return
	 * @throws WTException
	 * @throws ViewException
	 * @throws WTPropertyVetoException
	 */
	public static WTPartStandardConfigSpec getConfigSpecByView(String viewName)
			throws ViewException, WTException, WTPropertyVetoException {
		View viewObj = ViewHelper.service.getView(viewName);
		WTPartStandardConfigSpec standardConfig = WTPartHelper.service.findWTPartConfigSpec().getStandard();
		standardConfig.setView(viewObj);
		return standardConfig;
	}

	/**
	 * 获取物料的生效地
	 * 
	 * @param part 当前物料
	 * @return 生效地数组
	 * @throws RemoteException
	 * @throws WTException
	 */
	/*
	 * public static String[] getEffectiveSiteOfPart(WTPart part) throws
	 * RemoteException, WTException { System.out.println("Debug  BOM转厂   获取物料生效地：" +
	 * part.getNumber()); String effectiveSite = (String) IBAUtil.getIBAValue(part,
	 * "partNumberEffectiveSite"); if (null == effectiveSite) { effectiveSite = "";
	 * } System.out.println("Debug  BOM转厂   获取物料生效地检查前：" + effectiveSite);
	 * effectiveSite = effectiveSite.replace("，", ",");
	 * System.out.println("Debug  BOM转厂   获取物料生效地检查后：" + effectiveSite); String[]
	 * siteArray = effectiveSite.split(","); if (null == siteArray) { siteArray =
	 * new String[] { "" }; } return siteArray;
	 * 
	 * }
	 */

	public static String[] getEffectiveSiteOfPart(WTPart part) throws RemoteException, WTException {
		System.out.println("Debug  BOM转厂   获取物料生效地：" + part.getNumber());
		Vector effectiveSiteVector = (Vector) IBAUtil.getIBAValue2(part, "partNumberEffectiveSite");
		String effectiveSite = "";
		if (null == effectiveSiteVector) {
			return new String[] { "" };
		}
		for (int i = 0; i < effectiveSiteVector.size(); i++) {
			String temp = (String) effectiveSiteVector.get(i);
			effectiveSite = effectiveSite + temp + ",";

		}
		System.out.println("Debug  BOM转厂   获取物料生效地检查前：" + effectiveSite);
		effectiveSite = effectiveSite.replace("，", ",");
		System.out.println("Debug  BOM转厂   获取物料生效地检查后：" + effectiveSite);
		String[] siteArray = effectiveSite.split(",");
		if (null == siteArray) {
			siteArray = new String[] { "" };
		}

		for (int i = 0; i < siteArray.length; i++) {
			System.out.println("Debug  BOM 转厂 原生效地属性有：" + siteArray[i]);
		}
		return siteArray;

	}

	/**
	 * 获取试制物料的集合
	 * 
	 * @param commandBean
	 * @return
	 * @throws RemoteException
	 * @throws WTException
	 * @throws InvocationTargetException
	 * @throws WTPropertyVetoException
	 */
	public static ArrayList getTrialWTpartVector(NmCommandBean commandBean)
			throws RemoteException, WTException, InvocationTargetException, WTPropertyVetoException {
		ArrayList v = getTrialWTpart(commandBean);

		WTChangeOrder2 ecn = null;
		return v;
	}

	/**
	 * 获取试制物料的集合
	 * 
	 * @param commandBean
	 * @return 试制物料的集合
	 * @throws WTException
	 * @throws RemoteException
	 * @throws InvocationTargetException
	 * @throws WTPropertyVetoException
	 */
	public static ArrayList getTrialWTpart(NmCommandBean commandBean)
			throws WTException, RemoteException, InvocationTargetException, WTPropertyVetoException {
		System.out.println(">>>>>>>>>>>>>  getTrialWTpart  start");
		if (!RemoteMethodServer.ServerFlag) {
			String method = "getTrialWTpart";
			try {
				return (ArrayList) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null,
						new Class[] { NmCommandBean.class }, new Object[] { commandBean });
			} finally {

			}
		}
		ArrayList v = new ArrayList();
		ArrayList arraylist1 = commandBean.getSelectedOidForPopup();
		if (arraylist1 == null || arraylist1.size() <= 0) {
			throw new WTException("没有获取到要试制的部件对象！");
		}
		Iterator iterator = arraylist1.iterator();
		while (iterator.hasNext()) {
			Object obj = iterator.next();
			NmOid nmoid = NmCommandBean.getOidFromObject(obj);
			WTObject selectObj = (WTObject) nmoid.getRefObject();
			if (selectObj instanceof WTPart) {
				Hashtable<String, String> table = new Hashtable<String, String>();
				WTPart part = (WTPart) selectObj;
				if (isObjectCheckedOut(part)) {
					throw new WTException("编号为    " + part.getNumber() + "的部件被检出,不能试制!");
				}

				if (isObjectType(part, "SemiFinishedGood") || isObjectType(part, "C4") || isObjectType(part, "CF")
						|| isObjectType(part, "FinishedGood") || is168VirtualPart(part)) {
					String state = part.getLifeCycleState().getStringValue();
					if (state.contains("NewProduct") || state.contains("MassProductionRelease")) {

						System.out.println("Debug 试制    选择要试制的物料编号是：" + part.getNumber());

						table.put("number", part.getNumber());
						table.put("name", part.getName());
						table.put("version", part.getIterationDisplayIdentifier().toString());
						// if(isAllowPrint(selectObj));
						v.add(table);
					}
				}
			}

		}
		System.out.println("<<<<<<<<<<<<<<  getTrialWTpart  end");
		return v;

	}

	/**
	 * 判断是否为编号以168开头的虚拟件（其实，本质也是原材料）
	 * 
	 * @param part
	 * @return
	 */
	private static boolean is168VirtualPart(WTPart part) {
		boolean is168VirtualPart = false;

		if (part != null) {
			String partNumber = part.getNumber();

			if (partNumber != null && partNumber.startsWith("168")) {

				// 判断是否为虚拟件
				if (isVirtualPart(part)) {
					is168VirtualPart = true;
				}
			}
		}

		return is168VirtualPart;
	}

	private static boolean isVirtualPart(WTPart part) {
		boolean isVirtualPart = false;

		Source source = part.getSource();
		if (source != null) {
			String virtualPart = source.getStringValue();
			if (virtualPart.endsWith(".PHANTOM")) {
				isVirtualPart = true;
			}
		}

		return isVirtualPart;
	}

	/**
	 * 
	 * @param commandBean
	 * @return
	 * @throws WTException
	 */
	public static String getTrialWTpartView(NmCommandBean commandBean) throws WTException {
		String viewName = "";
		ArrayList arraylist1 = commandBean.getSelectedOidForPopup();
		if (arraylist1 == null || arraylist1.size() <= 0) {
			throw new WTException("没有获取到要试制的部件对象！");
		}
		Iterator iterator = arraylist1.iterator();
		Object obj = iterator.next();
		NmOid nmoid = NmCommandBean.getOidFromObject(obj);
		WTObject selectObj = (WTObject) nmoid.getRefObject();
		if (selectObj instanceof WTPart) {
			WTPart part = (WTPart) selectObj;
			viewName = part.getViewName();
		}
		return viewName;

	}

	/**
	 * 试制管理 生成试制建
	 * 
	 * @param numbers
	 * @param newNumbers
	 * @return
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static String trialManager(String numbers, String newNumbers, String viewName)
			throws WTException, WTPropertyVetoException {
		if (null == viewName || viewName.equals("")) {
			viewName = "Design";
		}

		WTPrincipal curUser = SessionHelper.manager.getPrincipal();
		SessionHelper.manager.setAdministrator();

		String state = "0";
		Hashtable<String, String> table = new Hashtable<String, String>();
		try {
			System.out.println(">>>>>>>>>>>>>  trialManager  start");
			String[] numberArray = numbers.split(",");
			String[] newNumbersArray = newNumbers.split(",");
			for (int i = 0; i < numberArray.length; i++) {
				String number = numberArray[i];
				String newNuber = newNumbersArray[i] + "-T";

				System.out.println("Debug 试制    原编号：" + number);
				System.out.println("Debug 试制    新建编号：" + newNuber);
				// ChangeTaskRoleParticipantHelper
				WTPart oldPart = CoreUtil.getWTPartByNumberAndView(number, viewName);
				if (null == oldPart) {
					throw new WTException("没有获取到试制的原部件对象！");
				}

				if ((isObjectType(oldPart, "RawMaterial") || isObjectType(oldPart, "TwoLevelMaterial"))
						&& (!is168VirtualPart(oldPart))) {
					continue;
				}

				table.put(number, newNuber);
				WTPart newpart = saveNewPart(oldPart);

				WTPart part = getWTPartByNumber(newNuber);
				if (null != part) {
					return "2";
				}

				newpart = (WTPart) LifeCycleHelper.service.setLifeCycleState(newpart, State.INWORK);
				Identified partidentified = (Identified) newpart.getMaster();
				WTPartMasterIdentity partmasteridentity = (WTPartMasterIdentity) partidentified
						.getIdentificationObject();
				partmasteridentity.setNumber(newNuber);
				partidentified = IdentityHelper.service.changeIdentity(partidentified, partmasteridentity); // 更新名称
				PersistenceServerHelper.manager.update(partidentified);
				newpart = (WTPart) PersistenceHelper.manager.refresh(newpart);

			}
			System.out.println("Debug 试制    要试制物料的个数：" + numberArray.length);
			if (numberArray.length > 1) {
				Vector<String> numberVector = new Vector<String>();
				for (Iterator it = table.keySet().iterator(); it.hasNext();) {
					String number = (String) it.next();
					String newNumber = table.get(number);
					System.out.println("Debug 试制    替换link关系：" + newNumber);
					WTPart part = CoreUtil.getWTPartByNumberAndView(newNumber, viewName);
					numberVector = replaceLinkOfTrailPart(part, table, viewName, numberVector,
							getConfigSpecByView(viewName));
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		SessionHelper.manager.setPrincipal(curUser.getName());
		System.out.println("<<<<<<<<<<<<<<  trialManager  end");
		return state;

	}

	/**
	 * 试制时替换部件中的结构
	 * 
	 * @param part
	 * @param table
	 * @param viewName
	 * @param numbers
	 * @param spec
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 * @throws WTPropertyVetoException
	 */
	public static Vector replaceLinkOfTrailPart(WTPart part, Hashtable<String, String> table, String viewName,
			Vector<String> numbers, WTPartStandardConfigSpec spec)
			throws WTException, RemoteException, WTPropertyVetoException {
		System.out.println(">>>>>>>>>>>>>>  replaceLinkOfTrailPart  start");
		String num = part.getNumber();
		System.out.println("Debug 试制    当前递归的物料为:" + num);
		if (numbers.contains(num))
			return numbers;
		QueryResult qr = WTPartHelper.service.getUsesWTParts(part, spec);
		System.out.println("Debug 试制 获取BOM长度qr.size=" + qr.size());
		String tempPartNumber = "";
		while ((qr != null) && (qr.hasMoreElements())) {
			System.out.println(">>>>>>>>>>>>>>>>>.come in while");
			WTPart wtpart = null;
			WTPartMaster partMaster = null;
			Persistable[] apersistable = (Persistable[]) qr.nextElement();
			WTPartUsageLink usageLink = (WTPartUsageLink) apersistable[0];
			if ((apersistable[1] instanceof WTPart)) {
				try {
					wtpart = (WTPart) apersistable[1];
				} catch (Exception ex1) {
					continue;
				}
			} else if ((apersistable[1] instanceof WTPartMaster)) {
				try {
					wtpart = CoreUtil.getWTPartByMasterAndView((WTPartMaster) apersistable[1], viewName);
				} catch (Exception ex) {
					continue;
				}
			}
			String currentNumber = wtpart.getNumber();
			System.out.println("Debug 试制 ：当前子键的编号：" + currentNumber);
			if (table.containsKey(currentNumber)) {
				String newNumber = table.get(currentNumber);
				PersistenceServerHelper.manager.remove(usageLink);

				LineNumber line = usageLink.getLineNumber();
				Quantity qu = usageLink.getQuantity();
				String ll = (String) IBAUtil.getIBAValue(usageLink, "Yield");
				if (null == ll) {
					System.out.println("Debug 试制 获取到的良率为null");
					ll = "";
				}
				Hashtable attributes = new Hashtable();
				attributes.put("Yield", ll);

				System.out.println("Debug 试制    要替换的零部件的编号：" + newNumber);
				WTPart newPart = getWTPartByNumber(newNumber);
				WTPartUsageLink link = WTPartUsageLink.newWTPartUsageLink(part, (WTPartMaster) newPart.getMaster());
				link.setQuantity(qu);
				link.setLineNumber(line);
				PersistenceServerHelper.manager.insert(link);
				IBAUtil.setSoftTypeIBAValues(link, attributes);
				numbers.add(newNumber);
			}
			replaceLinkOfTrailPart(wtpart, table, viewName, numbers, spec);
		}
		System.out.println("<<<<<<<<<<<<<  replaceLinkOfTrailPart  end");
		return numbers;
	}

	/**
	 * 判断对象类型是否为指定的内部关键字类型
	 * 
	 * @param object 对象；
	 * @param object 内部关键字；
	 * @return boolean 是指定的类型返回true；不是返回false
	 */
	public static boolean isObjectType(WTObject object, String objectType) {
		if (objectType.equals("") || objectType == null || object == null)
			return false;
		TypeIdentifier typeidentifier = TypedUtility.getTypeIdentifier(object);
		String typeName = typeidentifier.getTypename();
		if (typeName.indexOf(objectType) >= 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断某一特定对象是否处于检出状态
	 * 
	 * @param wto
	 * @return
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static boolean isObjectCheckedOut(WTObject wto) throws WTException, WTPropertyVetoException {
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			if ((wto instanceof Workable) && (wto instanceof CabinetBased)
					&& (CheckInOutTaskLogic.isCheckedOut((Workable) wto)
							|| FolderHelper.inPersonalCabinet((CabinetBased) wto))) {
				return true;
			} else
				return false;
		} /*
			 * catch (Exception e) { e.printStackTrace(); }
			 */finally {
			SessionServerHelper.manager.setAccessEnforced(flag);
		}
		// return false;
	}

	/**
	 * 获取要转厂物料的编号
	 * 
	 * @param commandBean
	 * @return
	 * @throws RemoteException
	 * @throws InvocationTargetException
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static String getTransitFactoryPartNumbers(NmCommandBean commandBean)
			throws RemoteException, InvocationTargetException, WTException, WTPropertyVetoException {
		System.out.println(">>>>>>>>>>>>>  getTransitFactoryPartNumbers  start");
		String numbers = "";
		if (!RemoteMethodServer.ServerFlag) {
			String method = "getTransitFactoryPartNumbers";
			try {
				return (String) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null,
						new Class[] { NmCommandBean.class }, new Object[] { commandBean });
			} finally {

			}
		}
		ArrayList arraylist1 = commandBean.getSelectedOidForPopup();
		if (arraylist1 == null || arraylist1.size() <= 0) {
			throw new WTException("没有获取到要要转厂的的部件对象！");
		}
		Iterator iterator = arraylist1.iterator();
		while (iterator.hasNext()) {
			Object obj = iterator.next();
			NmOid nmoid = NmCommandBean.getOidFromObject(obj);
			WTObject selectObj = (WTObject) nmoid.getRefObject();
			if (selectObj instanceof WTPart) {
				WTPart part = (WTPart) selectObj;

				if (isObjectType(part, "SemiFinishedGood") || isObjectType(part, "C4") || isObjectType(part, "CF")
						|| isObjectType(part, "FinishedGood")) {
					if (isObjectCheckedOut(part)) {
						throw new WTException("编号为    " + part.getNumber() + "的部件被检出,不能转厂!");
					}

					String state = part.getLifeCycleState().getStringValue();
					if (state.contains("NewProduct") || state.contains("MassProductionRelease")) {

					} else {
						continue;
					}
					if (part.getNumber().endsWith("-T")) {
						continue;
					}
					if (!part.getViewName().equals("Design")) {
						continue;
					}
					System.out.println("Debug 结构中转厂    选择要转厂物料编号是：" + part.getNumber());

					numbers = numbers + part.getNumber() + ",";

				} else {
					continue;
				}

			}
		}
		System.out.println("Debug is  zhuan chang numbers :" + numbers);
		System.out.println("<<<<<<<<<<<<<<  getTransitFactoryPartNumbers  end");
		if (numbers.equals("")) {
			throw new WTException("没有符合条件的试制对象！");
		}
		return numbers;
	}

	public static String transitFactoryInStrue(String numbers, String factorys) throws WTException {
		String state = "0";
		WTPrincipal curUser = SessionHelper.manager.getPrincipal();
		SessionHelper.manager.setAdministrator();

		try {
			System.out.println(">>>>>>>>>>>>>  transitFactoryInStrue  start");
			System.out.println("Debug is  zhuan chang numbers :" + numbers);
			System.out.println("Debug is  zhuan chang factorys  :" + factorys);
			String[] numberArray = numbers.split(",");
			String[] factoryArray = factorys.split(",");
			System.out.println("Debug   huo qu dao wu liao de ge shu :  " + numberArray.length);
			for (int i = 0; i < numberArray.length; i++) {
				// String setfactoryIBA = "";
				String number = numberArray[i];
				System.out.println("Debug transit factory   current number  is：" + number);
				WTPart part = getWTPartByNumberAndView(number, "Design");
				if (null == part) {
					throw new WTException("没有获取到对应的设计视图对象！");
				}

				if (isObjectType(part, "SemiFinishedGood") || isObjectType(part, "C4") || isObjectType(part, "CF")
						|| isObjectType(part, "FinishedGood")) {

					String existFactory = (String) IBAUtil.getIBAValue(part, "partNumberEffectiveSite");
					System.out.println("Debug  BOM转厂   已经存在的物料生效地：" + existFactory);
					PartCommands.setEffectiveSiteOfFinishGood(part, PartCommands.getConfigSpec(), factorys);

					String[] setFactoryArray = factorys.split(",");
					for (int m = 0; m < setFactoryArray.length; m++) {
						String temp = setFactoryArray[m];
						System.out.println("Debug  current transit veiw ：" + temp);
						if (existFactory.contains(temp)) {
							continue;
						}
						WTPart viewPart = null;
						viewPart = getWTPartByNumberAndView(number, temp);
						if (null == viewPart) {
							System.out.println("Debug   jie gou zhong zhuan chang shitu bu cun zai：" + temp);
							try {
								viewPart = (WTPart) ViewHelper.service.newBranchForView(part, temp);
								viewPart = (WTPart) PersistenceHelper.manager.save(viewPart);
								viewPart = (WTPart) LifeCycleHelper.service.setLifeCycleState(viewPart, State.INWORK);
								viewPart = (WTPart) PersistenceHelper.manager.refresh(viewPart);

								// 多值枚举IBA属性赋值
								// IBAUtil.forceSetIBAValue(viewPart,
								// "partNumberEffectiveSite", temp);
								CusIBAUtil.forceSetEnumIBAValue(viewPart, "partNumberEffectiveSite", temp);
							} catch (WTPropertyVetoException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {
							System.out.println("Debug   yao zhuan de view is exits：" + temp);
						}

						System.out.println("Debug   current  i  value :" + m);
					}

				} else {
					continue;
				}

			}
		} catch (Exception e) {

			state = "1";
			System.out.println(e);
		}
		SessionHelper.manager.setPrincipal(curUser.getName());
		System.out.println("<<<<<<<<<<<<<<  transitFactoryInStrue  end");
		return state;
	}

	/**
	 * 根据编号和视图查询对应最新视图版本的零部件.
	 * 
	 * @author Harry Cao
	 * @param number
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByNumberAndView(String number, String view) throws WTException {
		WTPartMaster master = getWTPartMasterByNumber(number);
		if (master == null)
			return null;
		else
			return getWTPartByMasterAndView(master, view);
	}

	/**
	 * 根据零部件的编号查找零部件的主数据(master)
	 * 
	 * @author Harry Cao
	 * @param partNumber
	 * @return
	 * @throws WTException
	 */
	public static WTPartMaster getWTPartMasterByNumber(String partNumber) throws WTException {
		WTPartMaster master = null;
		QuerySpec qs = null;
		QueryResult qr = null;
		qs = new QuerySpec(WTPartMaster.class);
		// 定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
				partNumber);
		qs.appendSearchCondition(sc);
		qr = PersistenceHelper.manager.find(qs);
		if (qr.hasMoreElements()) {
			master = (WTPartMaster) qr.nextElement();
		}
		return master;
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByMasterAndView(WTPartMaster master, String view) throws WTException {
		WTPart part = null;
		// 根据视图名称获取视图对象
		View viewObj = ViewHelper.service.getView(view);

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(viewObj, null);
		try {
			standardConfig.setView(viewObj);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		QueryResult qr1 = ConfigHelper.service.filteredIterationsOf(master, standardConfig);
		if (qr1.hasMoreElements()) {
			part = (WTPart) qr1.nextElement();
			if (!part.getViewName().equals(view))
				return null;
			System.out.println("部件的视图：" + part.getViewName());
		}

		return part;
	}

	/**
	 * 创建成品
	 * 
	 * @param number   编号
	 * @param name     名称
	 * @param ibaTable IBA
	 * @return 创建好的成品
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @throws UnsupportedEncodingException
	 */
	public static WTPart createFinishedGood(String number, String name,
			Hashtable ibaTable, WTDocument doc) throws WTException,
			WTPropertyVetoException, UnsupportedEncodingException {

		// String localtion = (String)
		// PropertiesUtil.getInstance().readProperties().get("finishedLocation");
		// localtion = new String(localtion.getBytes("ISO8859-1"),
		// System.getProperty("file.encoding"));
		// System.out.println("Debug 创建成品   成品创建的上下文为："+localtion);
		// if(localtion==null||localtion.equals(""))
		// {
		// throw new WTException("没有获取到成品创建的位置");
		// }

		WTPartMaster temp = CoreUtil.getWTPartMasterByNumber(number);
		if (null != temp) {
			throw new WTException("从接口表中获取到的成品编号在系统中已经存在，所以无法创建成品，请检查！");
		}
		WTPart part = WTPart.newWTPart();
		ViewReference viewRef = null;
		View view = ViewHelper.service.getView("Design");
		viewRef = ViewReference.newViewReference(view);
		part.setEndItem(true);
		part.setName(name);
		part.setNumber(number);
		part.setView(viewRef);
		QuantityUnit unit = QuantityUnit.toQuantityUnit("PCS");
		Source source = Source.toSource("make");

		// WTContainer con = getLibrayContainer(localtion);
		WTContainer con = doc.getContainer();
		if (null == con) {
			throw new WTException("没有获取到物料库");
		}

		WTContainerRef ref = WTContainerRef.newWTContainerRef(con);
		String foldStr = "/Default";
		Folder folder = FolderHelper.service.getFolder(foldStr, ref);
		part.setContainer(con);
		if (folder != null) {
			FolderHelper.assignLocation(part, folder);
		}
		part.setDefaultUnit(unit);
		part.setSource(source);
		String softTypeLogicId = "cn.tianma.FinishedGood";
		LoadValue.setType(part, softTypeLogicId);

		// 修改成品的创建者为RFQ文档的创建者
		CommonPDMUtil.setCreator(part, doc.getCreator());

		part = (WTPart) PersistenceHelper.manager.store(part);
		part = (WTPart) LifeCycleHelper.service.setLifeCycleState(part,
				State.INWORK);
		IBAUtil.setSoftTypeIBAValues(part, ibaTable);
		return part;

	}
	
	/**
	 * rfq创建成品
	 * 
	 * @param number   编号
	 * @param name     名称
	 * @param ibaTable IBA
	 * @return 创建好的成品
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @throws UnsupportedEncodingException
	 */
	public static WTPart createRFQFinishedGood(String number, String name, Hashtable ibaTable, WTDocument doc, WTUser creator)
			throws WTException, WTPropertyVetoException, UnsupportedEncodingException {

		// String localtion = (String)
		// PropertiesUtil.getInstance().readProperties().get("finishedLocation");
		// localtion = new String(localtion.getBytes("ISO8859-1"),
		// System.getProperty("file.encoding"));
		// System.out.println("Debug 创建成品 成品创建的上下文为："+localtion);
		// if(localtion==null||localtion.equals(""))
		// {
		// throw new WTException("没有获取到成品创建的位置");
		// }

		WTPartMaster temp = CoreUtil.getWTPartMasterByNumber(number);
		if (null != temp) {
			throw new WTException("从接口表中获取到的成品编号在系统中已经存在，所以无法创建成品，请检查！");
		}
		WTPart part = WTPart.newWTPart();
		ViewReference viewRef = null;
		View view = ViewHelper.service.getView("Design");
		viewRef = ViewReference.newViewReference(view);
		part.setEndItem(true);
		part.setName(name);
		part.setNumber(number);
		part.setView(viewRef);
		QuantityUnit unit = QuantityUnit.toQuantityUnit("PCS");
		Source source = Source.toSource("make");

		// WTContainer con = getLibrayContainer(localtion);
		if (doc == null) {
			//规定成品的存放位置
			String FOLDER = "/Default"; // 创建文件夹
			String secFolder = "/成品物料";
			WTContainer con = ECOCRUDUtil.getContainerByName("物料库");
			WTContainerRef containerRef = WTContainerRef.newWTContainerRef(con);
			// 设置文件夹
			Folder location = null;
			// 查询文件夹是否存在
			try {
				location = FolderHelper.service.getFolder(FOLDER + secFolder, containerRef);
			} catch (Exception e) {
				location = null;
			}
			// 若文件夹不存在，则创建该文件夹
			if (location == null)
				location = FolderHelper.service.saveFolderPath(FOLDER + secFolder, containerRef);
			// 设置文件夹到part对象
			if (location != null) {
				WTValuedHashMap map = new WTValuedHashMap();
				map.put(part, location);
				FolderHelper.assignLocations(map);
			}
			if (creator != null) {
				WTPrincipalReference prinref = WTPrincipalReference.newWTPrincipalReference(creator);
				CommonPDMUtil.setCreator(part, prinref);
				System.out.println("------创建者：" + creator.getName());
			}
			Folder folder = FolderHelper.service.getFolder(FOLDER + secFolder, containerRef);
			FolderHelper.assignLocation((FolderEntry) part, folder);
		} else {
			
			//根据rfq文档设置成品的存放位置
			WTContainer con = doc.getContainer();
			if (null == con) {
				throw new WTException("没有获取到物料库");
			}

			WTContainerRef ref = WTContainerRef.newWTContainerRef(con);
			String foldStr = "/Default";
			Folder folder = FolderHelper.service.getFolder(foldStr, ref);
			part.setContainer(con);
			if (folder != null) {
				FolderHelper.assignLocation(part, folder);
			}
			// 修改成品的创建者为RFQ文档的创建者
			CommonPDMUtil.setCreator(part, doc.getCreator());
		}

		part.setDefaultUnit(unit);
		part.setSource(source);
		String softTypeLogicId = "cn.tianma.FinishedGood";
		LoadValue.setType(part, softTypeLogicId);
		part = (WTPart) PersistenceHelper.manager.store(part);
		part = (WTPart) LifeCycleHelper.service.setLifeCycleState(part, State.INWORK);
		IBAUtil.setSoftTypeIBAValues(part, ibaTable);
		return part;

	}

	/**
	 * 根据名称获取存储库
	 * 
	 * @param s
	 * @return
	 * @throws QueryException
	 * @throws WTException
	 */
	public static WTContainer getLibrayContainer(String s) throws wt.query.QueryException, wt.util.WTException {
		QuerySpec queryspec = new QuerySpec(WTLibrary.class);
		queryspec.appendSearchCondition(new SearchCondition(WTLibrary.class, WTLibrary.NAME, SearchCondition.LIKE, s));
		QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
		WTContainer wtcontainer = null;
		while (queryresult.hasMoreElements()) {
			Object obj = queryresult.nextElement();
			if (obj instanceof WTLibrary)
				wtcontainer = (WTLibrary) obj;
		}
		return wtcontainer;

	}

	public static void setPartNumber(WTObject obj, String number) throws WTException, WTPropertyVetoException {
		WTPart part = (WTPart) obj;
		Identified partidentified = (Identified) part.getMaster();
		WTPartMasterIdentity partmasteridentity = (WTPartMasterIdentity) partidentified.getIdentificationObject();
		partmasteridentity.setNumber(number);
		partidentified = IdentityHelper.service.changeIdentity(partidentified, partmasteridentity); // 更新名称
		PersistenceServerHelper.manager.update(partidentified);
		part = (WTPart) PersistenceHelper.manager.refresh(part);
	}

	/**
	 * 判断字符窜是否位数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isDecimal(String str) {
		if (str.matches("[\\d]+") || str.matches("[\\d.]+")) {
			return true;
		}
		return false;
	}

	public static char toUpper(char ch) {
		if (ch <= 'z' && ch >= 'a') {
			return (char) (ch - 32);
		}
		return ch;
	}

	public static WTPart getWTPartByNumViewAndVersion(String number, String view, String version) throws WTException {
		WTPart part = null;

		QuerySpec qs = new QuerySpec(WTPartMaster.class);

		// 定义搜索条件，以零部件编号方式在master中搜索
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
				number);
		qs.appendSearchCondition(sc);

		QueryResult qr = PersistenceHelper.manager.find(qs);

		while (qr.hasMoreElements()) {
			WTPartMaster master = (WTPartMaster) qr.nextElement();

			if (master != null) {
				part = getWTPartByNumViewAndVersion(master, view, version);
				if (null != part)
					break;
			}
		}

		return part;
	}

	/**
	 * 根据零部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByNumViewAndVersion(WTPartMaster master, String view, String version)
			throws WTException {
		WTPart part = null;
		// 根据视图名称获取视图对象
		View viewObj = ViewHelper.service.getView(view);

		// 根据视图构造产品结构配置规范
		WTPartStandardConfigSpec standardConfig = WTPartStandardConfigSpec.newWTPartStandardConfigSpec(viewObj, null);
		try {
			standardConfig.setView(viewObj);
		} catch (WTPropertyVetoException wpve) {
			throw new WTException(wpve);
		}

		// 根据master和视图获取对应最新的视图版本零部件
		// QueryResult qr = ConfigHelper.service.filteredIterationsOf(master,
		// standardConfig);
		QueryResult qr = VersionControlHelper.service.allIterationsOf(master);
		// CoreUtil.getw

		System.out.println(">>>>> 根据编号和视图获取到的零部件对象数量为：" + qr.size());

		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();

			String partVersion = getVersion(part);
			if (partVersion.equals(version)) {
				return part;
			}
		}

		return null;
	}

	/**
	 * 获取对象的大小版本组成的版本序列值，形如： A.1
	 * 
	 * @param revisionControlled
	 * @return
	 */
	public static String getVersion(RevisionControlled revisionControlled) {

		String version = "";

		if (revisionControlled != null) {
			// 获取大版本
			String majorVersion = revisionControlled.getVersionIdentifier().getValue();

			// 获取小版本
			String minorVersion = revisionControlled.getIterationIdentifier().getValue();

			version = majorVersion + "." + minorVersion;
		}
		System.out.println("Debug 版本进阶 获取到的版本：" + version);
		return version;
	}

	public static void setSemiGoodsAuditInfoToIBA(String prcie, WTObject obj) throws WTException {
		if (obj instanceof WTObject) {

			System.out.println("Debug 原材料编码申请流程     设置IBA 价格：" + prcie);
			// add kwang 2013-12-11 添加判断条件价格不为空的时候设置
			if (prcie != null) {
				WTPart part = (WTPart) obj;
				Hashtable<String, String> table = new Hashtable<String, String>();

				table.put("partStandardCost", prcie);

				IBAUtil.setSoftTypeIBAValues(part, table);
			}
		} else {
			throw new WTException("主要业务对象不是WTPart，不能设置ＩＢＡ，请检查");
		}
	}

	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 * 
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
			String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}
}
